using Microsoft.EntityFrameworkCore;
using Microsoft.OpenApi.Models;
using System.Reflection;
using TaskProject;
using TaskProject.InfrasIntructure;
using TaskProject.InfrasIntructure.Implement;
using TaskProject.InfrasIntructure.Interface;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddDbContext<TaskDbContext>(a => a.UseSqlServer(builder.Configuration.GetConnectionString("conn")));
builder.Services.AddScoped<IDatabaseContext, DatabaseContext>();
builder.Services.AddScoped<DatabaseContext>();
builder.Services.AddScoped(typeof(IBaseRepository<>), typeof(BaseRepository<>));
builder.Services.AddHttpContextAccessor();
//builder.Services.AddAutoMapper(typeof(MyMapper));
//ע���н���
builder.Services.AddMediatR(cfg =>
{
    cfg.RegisterServicesFromAssemblies(Assembly.GetExecutingAssembly());
});
builder.Services.AddAutoMapper(typeof(MyMapper));
builder.Services.AddSwaggerGen(x =>
{
    string conn = AppDomain.CurrentDomain.BaseDirectory + "TaskProject.xml";

    x.IncludeXmlComments(conn, true);
    //x.AddServer(new OpenApiServer()
    //{
    //    Url = "/lineconsul",
    //    Description = "kongs"
    //});
});

var app = builder.Build();

// Configure the HTTP request pipeline.
//if (app.Environment.IsDevelopment())
//{
    app.UseSwagger();
    app.UseSwaggerUI();
//}
// �����м��֮ǰ��ʼ�����ݿ�
using (var scope = app.Services.CreateScope())
{
    try
    {
        var dbContext = scope.ServiceProvider.GetRequiredService<IDatabaseContext>();
        dbContext.InitializeDatabase();
    }
    catch (Exception ex)
    {
        var logger = scope.ServiceProvider.GetRequiredService<ILogger<Program>>();
        logger.LogError(ex, "���ݿ��ʼ��ʧ��");
    }
}

app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
app.UseAuthorization();

app.MapControllers();

app.Run();
